package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.CheckGroupDao;
import com.itheima.health.dao.SetmealDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author hm
 * @version 1.0
 * @date Created in 2024/7/14 16:59
 */
@Service
public class SetmealServiceImpl implements SetmealService {
    /**
     * 获取所有套餐信息
     * @return
     */
    @Resource
    private SetmealDao setmealDao;


    @Resource
    private CheckGroupDao checkGroupDao;
    /**
     * 获取所有套餐信息
     * @return
     */
    @Override
    public List<Setmeal> findAll() {
        // 1.调用DAO获取所有套餐信息
        List<Setmeal> list = setmealDao.findAll();
        // 2.返回获取所有套餐信息
        return list;
    }

    @Override
    public Setmeal findFullSetmealById(Integer id) {
        Setmeal fullSetmealById = setmealDao.findFullSetmealById(id);
        List<CheckGroup> checkGroups = checkGroupDao.findBySetmealId(id);
        fullSetmealById.setCheckGroups(checkGroups);
        return fullSetmealById;
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findFullSetmealById(id);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> page = setmealDao.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public List<Integer> findCheckGroupIds(Integer setmealId) {
        return setmealDao.findCheckGroupIds(setmealId);
    }

    @Override
    @Transactional
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        if (checkgroupIds.length != 0) {
            setmealDao.addCheckGroupId(setmeal.getId(), checkgroupIds);
        }
    }

    @Override
    @Transactional
    public void update(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.update(setmeal);
        setmealDao.deleteAssociatuon(setmeal.getId());
        if (checkgroupIds.length != 0){
            setmealDao.addCheckGroupId(setmeal.getId(),checkgroupIds);
        }
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        setmealDao.deleteAssociatuon(id);
        setmealDao.deleteById(id);
    }
}
